$(document).ready(function(){
    
    // Search on enter
    $('#paymentSearch').keypress(function (e) {
        if (e.which == 13) {
          searchByContractNumber();
          return false;    
        }
      });
    
    $("#contractId").val('');
    $("#contractId").val('');
    if($("#paymentSearch").val().length > 0)
    {
        searchByContractNumber();
    }else{
        $("#paymentSearch").val('');
    }
    
    $(".paymentCalc").on('keyup', function(){        
        calcThisRow($(this).attr('alt'));
        
    });
    
    
});

function searchByContractNumber()
{
    var contractNumber = $('#paymentSearch').val();
    if(contractNumber.length > 0)
    {   
        $.ajax({
            type: 'post',
            url: '/payment/searchByContractNumber/',
            data: {
                contractNumber : contractNumber
            },
            beforeSend: function(){
                $("#info_container").slideUp();
                $("#paymentGraphContainer").slideUp();
                $("#paymentTableContainer").slideUp();
                $("#submitBtn").slideUp();
                $.blockUI({ message: null });
                $("#schduleTbody").html('');                
                $(".errorContainer").remove();
            },
            dataType: "json",
            success: function (result) {
                
                if(result.status === 'success')
                {
                    
                    setInfo(result.data.REGISTER_NAME, result.data.NAME, result.data.LAST_NAME, result.data.PHONE_NUMBER, result.data.EMAIL);
                    
                    var n = [];
                    $.each(result.data.GRAPH.DUE, function( key, value ) {
                        
                        var tmpDate = (new Date(value.DATE)).getTime();
                        var tmpValue = value.VALUE;
                        var tmpOneItem = [tmpDate, tmpValue];
                        
                        n.push(tmpOneItem);
                        
                    });
                    
                    var r = [];
                    
                    $.each(result.data.GRAPH.PAID, function( key, value ) {
                        
                        var tmpDate = (new Date(value.DATE)).getTime();
                        var tmpValue = value.VALUE;
                        var tmpOneItem = [tmpDate, tmpValue];
                        
                        r.push(tmpOneItem);
                        
                    });
                    
                    drawGraph(n, r);
                    
                    if (typeof result.data.CREDIT_SCHEDULE !== 'undefined'){
                       drawPaymentTable(result.data.CREDIT_SCHEDULE);
                    }
                    
                    
                    
                    setCreditInformation(result.data.CREDIT);
                    
                    $("#contractId").val(contractNumber);
                    $("#creditId").val(result.data.CREDIT_ID);
                    $("#submitBtn").slideDown();
                }else{
                    $("#searchContractContainer").after('<div class="form-row errorContainer"><div class="col-md-12 text-center">Энэ гэрээний дугаараар олгосон зээл олдсонгүй ! </div></div>');
                }
            },
            error: function () {
                console.log('Search failed');
                $.unblockUI();
            }
        }).done(function(){
            $.unblockUI();
        });
    }else{
        alert('Гэрээний дугаар оруулана уу!');
    }
    
}

function drawGraph(n, r)
{
    if ($("#payment_chart").length > 0) {
        $.plot($("#payment_chart"), 
            [{data: n, label: "Төлөх ёстой"}, {data: r, label: "Төлсөн"}], 
            {
                series: {stack: 0, bars: {barWidth: .5, align: "center"}}, 
                grid: {hoverable: true, clickable: true}, 
                xaxis: {mode: "time", timeformat: "%Y-%m-%d"}, 
                lines: {"show": "true"}, 
                points: {"show": "true"}
            }
        )
        $("#paymentGraphContainer").slideDown();
    }
    
    
    function d(e, t) {
        return"<div style='text-shadow: 1px 2px 1px rgba(0,0,0,0.2); font-size: 11px; text-align:center; padding:2px; color: #FFF; line-height: 13px;'>" + e + "<br/>" + Math.round(t.percent) + "%</div>"
    }
    function v(e, t, n) {
        $('<div class="ftooltip">' + n + "</div>").css({position: "absolute", "z-index": "10", display: "none", top: t - 20, left: e, padding: "3px", "background-color": "rgba(0,0,0,0.5)", "font-size": "11px", "border-radius": "3px", color: "#FFF"}).appendTo("body").fadeIn(200)
    }

    var m = null;
    $("#payment_chart").bind("plothover", function(e, t, n) {
      $("#x").text(t.x.toFixed(2));
      $("#y").text(t.y.toFixed(2));
      if (n) {
        if (m != n.dataIndex) {
          m = n.dataIndex;
          $(".ftooltip").remove();
          var r = n.datapoint[0].toFixed(2), i = n.datapoint[1].toFixed(2);
          v(n.pageX, n.pageY, n.series.label + ": " + i)
        }
      } else {
        $(".ftooltip").remove();
        m = null
      }
    })
    
}

function drawPaymentTable(creditSchedule)
{
    $("#paymentTableContainer").slideDown();
    
    var html = '';
    var counter = 1;
    $.each( creditSchedule, function( key, value ) {
        html += '<tr><td>'+counter+'<input type="hidden" name="ids[]" value="' + value.ID + '"></td><td>' + value.TARGET_DATE.substr(0, 10) + '<input type="hidden" name="target_dates[]" value="'+value.TARGET_DATE.substr(0, 10)+'"></td><td class="currency">'+value.DAYS+'</td><td class="currency">'+value.MAIN_AMOUNT+'</td><td class="currency">'+value.INTEREST_AMOUNT+'</td><td class="currency totalAmount_'+counter+'">'+value.TOTAL_AMOUNT+'</td><td><input type="text" name="payments[]" class="currency payment_'+counter+' paymentCalc" alt="'+counter+'" onKeyup="calcThisRow(\''+counter+'\')" value="';
        if(value.PAID_AMOUNT !== null)
        {
            html += value.PAID_AMOUNT;
        }
        html +='"/></td><td><input type="text" name="balances[]" class="currency balance_'+counter+'" value="';
        
        if(value.BALANCE !== null){
            html += value.BALANCE;
        }
        html +='"></td></tr>';
        counter = counter + 1;
    });
    
    var hiddenScheduleRowNum = parseInt($("#hiddenScheduleRowNum").val());
    
    if(hiddenScheduleRowNum === 0)
    {
        $("#schduleTbody").html(html);
    }else{
        $("#schduleTbody").append(html);
    }
    
    hiddenScheduleRowNum++;
    $("#hiddenScheduleRowNum").val(hiddenScheduleRowNum);
    
    $(".currency").keyup(function() {
        $(this).formatCurrency();
    });
    
}

function calcThisRow(num)
{
    var totalAmount = parseFloat($(".totalAmount_"+num).html().replace(/,/g, ''));    
    var payment = parseFloat($(".payment_"+num).val().replace(/,/g, ''));
    var balance = 0;
    if(num > 1)
    {
        var tmpPrevCount = num - 1;
        var prev = parseFloat($(".balance_"+tmpPrevCount).val().replace(/,/g, ''));
        balance = prev - payment;
    }else{
        balance = totalAmount - payment;
    }
        
    if(isNaN(balance))
    {
        balance = null;
    }
    
    $(".balance_"+num).val(balance);
    $(".balance_"+num).formatCurrency({negativeFormat: '-%s%n'});
}

Date.prototype.yyyymmdd = function() {
   var yyyy = this.getFullYear().toString();
   var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based
   var dd  = this.getDate().toString();
   return yyyy + "-" + (mm[1]?mm:"0"+mm[0]) + "-" + (dd[1]?dd:"0"+dd[0]); // padding
};

function setCreditInformation(creditArray)
{
    $("#schedule_total_amount").html(creditArray.TOTAL_AMOUNT);
    $("#schedule_intereset").html(creditArray.INTEREST_PERCENT);
    $("#schedule_length").html(creditArray.SCHEDULE_LENGTH);
    $("#schedule_start_date").html(creditArray.BEGIN_DATE);
    $("#schedule_start_date").html(creditArray.BEGIN_DATE);
    $("#schedule_payment_start_date").html(creditArray.TARGET_DATE);
    
    $("#schedule_payment_type").html(creditArray.CREDIT_PAYMENT_TYPE_NAME);
    $("#schedule_amount_per_unit").html(creditArray.ONE_AMOUNT);
    $("#schedule_amount_per_unit").formatCurrency();
    
}

function setInfo(registerNumber, name, lastName, phone, email)
{
    $("#info_container").slideDown();
    
    $("#info_name").html(name);
    $("#info_family_name").html(lastName);
    $("#info_phone").html(phone);
    $("#info_email").html(email);
    
    
}
